<template>
  <view class="dashboard-container">
    <!-- 顶部提示栏 -->
    <view class="top-alert">
      <text class="alert-text">此平台为互联网非涉密平台，严禁处理、传输国家秘密</text>
    </view>
    
    <!-- 功能按钮区 -->
    <view class="function-grid">
      <view class="function-item" v-for="(item, index) in functionList" :key="index" @click="handleFunctionClick(item)">
        <view class="icon-wrapper">
          <image :src="item.tb" class="function-icon" mode="widthFix"></image>
          <view class="new-tag" v-if="item.isnew === '1'">NEW</view>
        </view>
        <text class="function-name">{{ item.name }}</text>
      </view>
    </view>
    
    <!-- 机构欠费统计 -->
    <view class="section-container" :class="{ 'full-width': !config.orgArrears.margin }">
      <view class="section-header">
        <view class="section-title-wrapper">
          <view class="red-square org-red"></view>
          <text class="section-title">机构欠费（万元）</text>
        </view>
        <text class="section-date">{{ updateTime }}</text>
      </view>
      
      <!-- 表格容器 -->
      <view class="table-container-wrapper">
        <!-- 移动模式用滚动容器，PC模式用普通容器 -->
        <view 
          :class="isMobile ? 'table-scroll-container' : 'table-full-container'"
          :style="isMobile ? { width: visibleWidth + 'rpx' } : {}"
        >
          <!-- 表格 -->
          <view 
            class="data-table org-table" 
            :style="isMobile ? { width: tableTotalWidth + 'rpx' } : { width: '100%' }"
          >
            <!-- 表头行 -->
            <view class="org-table-header table-header-fixed">
              <view 
                class="org-table-cell org-table-cell-fixed" 
                :style="isMobile ? 
                  { width: fixedColumnWidth + 'rpx' } : 
                  { width: fixedColumnWidth + '%' }"
              >
                单位
              </view>
              <view 
                class="org-table-cell org-table-cell-data" 
                v-for="(col, idx) in dataColumns" :key="idx"
                :style="isMobile ? 
                  { width: dataColumnWidth + 'rpx' } : 
                  { width: dataColumnWidth + '%' }"
              >
                {{ col }}
              </view>
            </view>
            
            <view class="table-body">
              <!-- 表格行 -->
              <view class="org-table-row" v-for="(row, index) in mergedJb2FeeSummaryList" :key="index">
                <view 
                  class="org-table-cell org-table-cell-fixed" 
                  :style="isMobile ? 
                    { width: fixedColumnWidth + 'rpx' } : 
                    { width: fixedColumnWidth + '%' }"
                >
                  {{ row.jb2Name }}
                </view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(row.totalFee) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(row.totalOverdue) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(row.jdFee) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(row.jdOverdue) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(row.ywFee) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(row.ywOverdue) }}</view>
              </view>
              
              <!-- 机构欠费合计行 -->
              <view class="org-table-row org-table-total">
                <view 
                  class="org-table-cell org-table-cell-fixed" 
                  :style="isMobile ? { width: fixedColumnWidth + 'rpx' } : { width: fixedColumnWidth + '%' }"
                >
                  <text style="font-weight: bold; color: #000000;">合计</text>
                </view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(orgTotal.totalFee) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(orgTotal.totalOverdue) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(orgTotal.jdFee) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(orgTotal.jdOverdue) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(orgTotal.ywFee) }}</view>
                <view class="org-table-cell org-table-cell-data" :style="isMobile ? { width: dataColumnWidth + 'rpx' } : { width: dataColumnWidth + '%' }">{{ formatToWan(orgTotal.ywOverdue) }}</view>
              </view>
            </view>
          </view>
        </view>
        
        <!-- 右侧遮罩层：仅移动模式显示 -->
        <view class="right-mask" :style="{ left: visibleWidth + 'rpx', display: isMobile ? 'block' : 'none' }"></view>
      </view>
    </view>
	
	<!-- 可视化切换 -->
	<view class="visualization-toggle" @click="handleVisualizationToggle">
	  <text class="visualization-text">趋势图</text>
	  <text 
		class="visualization-icon" 
		:style="{transform: showTrendChart ? 'rotate(180deg)' : 'rotate(0)'}"
	  >▲</text>
	</view>

    <!-- 统计图表区域 -->
    <view class="chart-container" :class="{ 'full-width': !config.trendAnalysis.margin }" v-if="showTrendChart">
      <view class="section-header">
        <text class="section-title">欠费趋势分析</text>
      </view>
      <view class="charts-wrapper">
        <qiun-data-charts 
          type="column"
          :opts="opts"
          :chartData="chartData"
          :disableScroll="true"  
          :ontouch="true"    
          canvasId="orgArrearsChart"
		  ref="chart"
          :style="{ width: '100%', height: chartHeight + 'px' }"
        ></qiun-data-charts>
      </view>
    </view>
    
    <!-- 专业欠费统计 -->
    <view class="section-container" :class="{ 'full-width': !config.profArrears.margin }">
      <view class="section-header">
        <view class="section-title-wrapper">
          <view class="red-square prof-purple"></view>
          <text class="section-title">专业欠费（万元）</text>
        </view>
        <text class="section-date">{{ updateTime }}</text>
      </view>
      
      <view class="data-table prof-table">
        <view class="prof-table-header">
          <view class="prof-table-cell">专业</view>
          <view class="prof-table-cell">欠费总计</view>
          <view class="prof-table-cell">逾期欠费</view>
        </view>
        
        <view class="table-body">
          <view class="prof-table-row" v-for="(row, index) in profArrearsData" :key="index"
                :class="['prof-row-' + (index % 2)]">
            <view class="prof-table-cell">{{ row.name }}</view>
            <view class="prof-table-cell">{{ formatToWan(row.hj) }}</view>
            <view class="prof-table-cell">{{ formatToWan(row.yqqf) }}</view>
          </view>
          
          <!-- 专业欠费合计行 -->
          <view class="prof-table-row prof-table-total">
            <view class="prof-table-cell">
              <text style="font-weight: bold; color: #000000;">合计</text>
            </view>
            <view class="prof-table-cell">{{ formatToWan(profTotal.hj) }}</view>
            <view class="prof-table-cell">{{ formatToWan(profTotal.yqqf) }}</view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 数据更新时间 -->
    <view class="update-time">
      数据更新时间：{{ updateTime }}
    </view>

    <view class="bottom-space"></view>
  </view>
</template>

<script>
import store from '../../common/store.js'
import utils from '../../common/utils'

export default {
  data() {
    return {
      chartData: {},
      chartHeight: 200,
      opts: {
        enableScroll: true,         
        legend: { show: false },
        xAxis: {
          disableGrid: true,
          itemCount: 5,             
          rotateLabel: true,
          marginTop: 8,				
          scrollShow: true,         
          scrollAlign: "left"       
        },
        yAxis: { 
          data: [{ min: 0 }],
          label: { name: "欠费金额（元）" }
        },
        extra: {
          column: {
            type: "group",
            width: 35,
            customColor: true
          }
        }
      },
      userInfo: store.getLoginInfo(),
      config: {
        orgArrears: { margin: true },
        trendAnalysis: { margin: true },
        profArrears: { margin: true }
      },
      functionList: [],
      mergedJb2FeeSummaryList: [],
      profArrearsData: [],
      updateTime: "2025-08-19 20:30:00",
	  showTrendChart: false,
      
      // 合计数据
      orgTotal: {
        jb2Name: '合计',
        totalFee: 0,
        totalOverdue: 0,
        jdFee: 0,
        jdOverdue: 0,
        ywFee: 0,
        ywOverdue: 0
      },
      profTotal: {
        name: '合计',
        hj: 0,
        yqqf: 0
      },
      
      // 移动模式参数（完全还原原始逻辑）
      visibleWidth: 0,        // 移动可视区域宽度(rpx)
      fixedColumnWidth: 0,    // 列宽（移动用rpx，PC用%）
      dataColumnWidth: 0,     // 数据列宽
      tableTotalWidth: 0,     // 移动表格总宽度
      dataColumns: ['综合欠费', '综合逾期', '寄递欠费', '寄递逾期', '邮务欠费', '邮务逾期'],
      isMobile: true,         // 是否为移动设备
      pcBreakpoint: 768,      // PC断点
      // 移动模式固定参数（确保与原始效果一致）
      mobileFixedRatio: 1.3,  // 固定列比例
      mobileVisibleDataCols: 4 // 移动可视数据列数
    };
  },
  onLoad() {
    uni.pageScrollTo({ scrollTop: 0, duration: 0 });
    this.calcChartHeight();
    this.calculateTableLayout();
  },
  onShow() {
    console.info("用户信息：" + JSON.stringify(this.userInfo));
    this.initPage();
  },
  onReady() {
    uni.onWindowResize(res => {
      this.calcChartHeight();
      this.calculateTableLayout();
      this.$nextTick(() => {
        this.$refs.chart && this.$refs.chart.repaint();
      });
    });
  },
  onUnload() {
    uni.offWindowResize();
  },
  methods: {
    formatToWan(num) {
      return this.$utils.formatToWan(num);
    },
    calcChartHeight() {
      const sysInfo = uni.getSystemInfoSync();
      this.isMobile = sysInfo.screenWidth <= this.pcBreakpoint;
      if (!this.isMobile) {
        this.chartHeight = Math.max(300, Math.min(400, sysInfo.windowWidth * 0.3));
      } else {
        this.chartHeight = Math.max(180, Math.min(300, sysInfo.windowWidth * 0.4));
      }
    },
    // 核心：严格分离移动和PC布局逻辑
    calculateTableLayout() {
      const sysInfo = uni.getSystemInfoSync();
      this.isMobile = sysInfo.screenWidth <= this.pcBreakpoint;
      const margin = this.config.orgArrears.margin ? 30 : 0;
      
      if (this.isMobile) {
        // 移动模式：完全还原原始逻辑
        const screenWidth = 750; // 固定使用750rpx标准
        const containerWidth = screenWidth - margin;
        const totalUnits = this.mobileFixedRatio + this.mobileVisibleDataCols;
        
        // 计算列宽
        this.dataColumnWidth = containerWidth / totalUnits;
        const minColWidth = 120; // 原始最小列宽
        
        if (this.dataColumnWidth < minColWidth) {
          this.dataColumnWidth = minColWidth;
          this.fixedColumnWidth = this.dataColumnWidth * this.mobileFixedRatio;
          this.visibleWidth = this.fixedColumnWidth + (this.mobileVisibleDataCols * this.dataColumnWidth) - 2;
        } else {
          this.fixedColumnWidth = this.dataColumnWidth * this.mobileFixedRatio;
          this.visibleWidth = containerWidth - 2;
        }
        
        // 表格总宽度（所有列）
        this.tableTotalWidth = this.fixedColumnWidth + 6 * this.dataColumnWidth;
      } else {
        // PC模式：铺满容器，显示所有列
        const totalDataCols = 6;
        const totalUnits = this.mobileFixedRatio + totalDataCols;
        this.dataColumnWidth = 100 / totalUnits; // 百分比
        this.fixedColumnWidth = this.dataColumnWidth * this.mobileFixedRatio;
      }
    },
    initPage: async function () {
      this.$utils.showLoading("数据加载中...");
      try {
        const timestamp = this.$utils.getTimestamp();
        const userInfo = uni.getStorageSync("userInfo");
        const enData = this.$utils.encrypt(
          JSON.stringify({ timestamp }),
          userInfo.aesKey,
          userInfo.aesIv
        );
        const res = await this.$myRequest.post_token(
          getApp().globalData.qfkbInit,
          { data: enData + "" }
        );
        
        this.$utils.hideLoading();
        if (res.code === 200) {
          const a = JSON.parse(utils.decrypt(
            res.data,
            userInfo.aesKey,
            userInfo.aesIv
          ));
		  
		  console.info("a:"+JSON.stringify(a));
          
          this.functionList = a.TqfkbBkList || [];
          this.mergedJb2FeeSummaryList = a.mergedJb2FeeSummaryList || [];
          this.profArrearsData = a.zyqfList || [];
          this.updateTime = a.rq || "2025-08-19 20:30:00";
          
          // 计算机构欠费合计
          this.orgTotal = {
            jb2Name: '合计',
            totalFee: 0,
            totalOverdue: 0,
            jdFee: 0,
            jdOverdue: 0,
            ywFee: 0,
            ywOverdue: 0
          };
          this.mergedJb2FeeSummaryList.forEach(item => {
            this.orgTotal.totalFee += Number(item.totalFee) || 0;
            this.orgTotal.totalOverdue += Number(item.totalOverdue) || 0;
            this.orgTotal.jdFee += Number(item.jdFee) || 0;
            this.orgTotal.jdOverdue += Number(item.jdOverdue) || 0;
            this.orgTotal.ywFee += Number(item.ywFee) || 0;
            this.orgTotal.ywOverdue += Number(item.ywOverdue) || 0;
          });
          
          // 计算专业欠费合计
          this.profTotal = {
            name: '合计',
            hj: 0,
            yqqf: 0
          };
          this.profArrearsData.forEach(item => {
            this.profTotal.hj += Number(item.hj) || 0;
            this.profTotal.yqqf += Number(item.yqqf) || 0;
          });
          
          this.chartData = {
            categories: this.mergedJb2FeeSummaryList.map(item => item.jb2Name),
            series: [{
              name: "欠费金额",
              data: this.mergedJb2FeeSummaryList.map(item => ({
                value: this.formatToWan(item.totalFee),
                color: item.ysdm
              }))
            }]
          };
          
          this.$nextTick(() => {
            this.$refs.chart && this.$refs.chart.repaint();
          });
        } else {
          this.$utils.toast(`数据加载失败！错误码[${res.code}]`);
        }
      } catch (e) {  
        this.$utils.hideLoading();
        console.error("数据加载异常：", e);
        this.$utils.toast("数据加载失败！" + e.message);           
      }
    },
    handleFunctionClick(item) {
      if (item.dz) {
        uni.navigateTo({ url: item.dz });
      } else {
        uni.showToast({
          title: '后台未配置该功能',
          icon: 'none',
          duration: 2000
        });
      }
    },
	handleVisualizationToggle() {
	  this.showTrendChart = !this.showTrendChart;
	  if (this.showTrendChart) {
		this.$nextTick(() => {
		  this.calcChartHeight();
		  setTimeout(() => {
			this.$refs.chart && this.$refs.chart.repaint();
		  }, 100);
		});
	  }
	},
  }
};
</script>

<style scoped>
/* 全局样式 */
page {
  overflow-x: hidden;
  width: 100%;
  box-sizing: border-box;
}

.dashboard-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  padding: 0;
  width: 100%;
  box-sizing: border-box;
}

/* 顶部提示栏 */
.top-alert {
  background-color: #ffffff;
  padding: 12rpx 15rpx;
  text-align: center;
  font-size: 24rpx;
  width: 100%;
  box-sizing: border-box;
}

.alert-text {
  color: #006400;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 功能按钮区 */
.function-grid {
  display: flex;
  flex-wrap: wrap;
  background-color: #ffffff;
  margin: 10rpx 15rpx 15rpx;
  border-radius: 6rpx;
  padding: 15rpx 5rpx;
  width: calc(100% - 30rpx);
  box-sizing: border-box;
}

.function-item {
  width: 25%;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15rpx 0;
  box-sizing: border-box;
}

.icon-wrapper {
  position: relative;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
  border-radius: 50%;
  margin-bottom: 10rpx;
}

.function-icon {
  width: 45rpx;
  height: 45rpx;
}

.new-tag {
  position: absolute;
  top: -5rpx;
  right: -5rpx;
  background-color: #ff4d4f;
  color: white;
  font-size: 20rpx;
  padding: 2rpx 8rpx;
  border-radius: 10rpx;
}

.function-name {
  font-size: 26rpx;
  color: #333333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  max-width: 90%;
  text-align: center;
}

/* 通用区块样式 */
.section-container {
  background-color: #ffffff;
  margin: 0 15rpx 15rpx;
  border-radius: 6rpx;
  overflow: hidden;
  width: calc(100% - 30rpx);
  box-sizing: border-box;
}

.full-width {
  margin-left: 0;
  margin-right: 0;
  width: 100%;
  border-radius: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 25rpx;
  border-bottom: 1px solid #f0f0f0;
  width: 100%;
  box-sizing: border-box;
}

.red-square {
  width: 20rpx;
  height: 20rpx;
  display: inline-block;
  margin-right: 15rpx;
}

.org-red {
  background-color: #e53e3e;
}

.prof-purple {
  background-color: #6b21a8;
}

.section-title-wrapper {
  display: flex;
  align-items: center;
}

.section-title {
  color: #1f2329;
  font-size: 30rpx;
  font-weight: 600;
}

.section-date {
  color: #86909c;
  font-size: 24rpx;
}

/* 表格容器 */
.table-container-wrapper {
  position: relative;
  width: 100%;
  overflow: hidden;
}

/* 移动模式滚动容器 */
.table-scroll-container {
  height: auto;
  min-height: 300rpx;
  overflow-x: auto;
  position: relative;
  -webkit-overflow-scrolling: touch;
  box-sizing: border-box;
}

/* PC模式容器（无滚动） */
.table-full-container {
  height: auto;
  min-height: 300rpx;
  overflow-x: hidden;
  box-sizing: border-box;
}

.right-mask {
  position: absolute;
  top: 0;
  height: 100%;
  width: 10rpx;
  background-color: #ffffff;
  z-index: 20;
  pointer-events: none;
}

.org-table {
  box-sizing: border-box;
}

.table-header-fixed {
  position: sticky;
  top: 0;
  z-index: 10;
  width: 100%;
  box-sizing: border-box;
}

.org-table-header {
  display: flex;
  color: #ffffff;
  font-weight: 500;
  background: linear-gradient(90deg, #d32f2f, #ff6659);
  box-sizing: border-box;
}

.org-table-cell {
  padding: 0 15rpx;
  height: 80rpx;
  text-align: center;
  font-size: 26rpx;
  border-right: 1px solid #ffffff;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  box-sizing: border-box;
}

.org-table-cell-fixed {
  position: sticky;
  left: 0;
  z-index: 5;
  flex: none;
  background: inherit;
}

.org-table-cell-data {
  flex: none;
  box-sizing: border-box;
}

.org-table-row {
  display: flex;
  width: 100%;
  box-sizing: border-box;
}

.org-table-row:nth-child(even) {
  background-color: #fff8f8;
}

.org-table-row:nth-child(odd) {
  background-color: #ffffff;
}

.org-table-cell:last-child {
  border-right: none !important;
}

.org-table-header .org-table-cell:last-child {
  border-bottom: none !important;
}

/* 机构欠费合计行样式 */
.org-table-total {
  background-color: #fff0f0;
  font-weight: bold;
}
.org-table-total .org-table-cell {

}

/* 移动设备响应式 */
@media screen and (max-width: 768px) {
  .org-table-cell {
    font-size: 26rpx;
    padding: 0 15rpx;
  }
  
  .section-title {
    font-size: 30rpx;
  }
}

/* PC设备样式 */
@media screen and (min-width: 769px) {
  .org-table-cell {
    height: 90rpx;
    font-size: 28rpx;
    padding: 0 25rpx;
  }

  .section-container {
    margin: 0 30rpx 15rpx;
  }
}

/* 专业欠费表格样式 */
.prof-table-header {
  display: flex;
  color: #ffffff;
  font-weight: 500;
  width: 100%;
  background: linear-gradient(90deg, #6b21a8, #a855f7);
}

.prof-table-cell {
  padding: 22rpx 8rpx;
  text-align: center;
  font-size: 26rpx;
  border-right: 1px solid #ffffff;
  border-bottom: 1px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1;
  box-sizing: border-box;
}

.prof-table-row {
  display: flex;
  width: 100%;
}

.prof-table-row.prof-row-0 {
  background-color: #fff5f5;
}

.prof-table-row.prof-row-1 {
  background-color: #ffffff;
}

.prof-table-cell:last-child {
  border-right: none;
}

/* 专业欠费合计行样式 */
.prof-table-total {
  background-color: #faf5ff;
  font-weight: bold;
}
.prof-table-total .prof-table-cell {
 
}

/* 图表区域 */
.chart-container {
  background-color: #ffffff;
  margin: 0 15rpx 15rpx;
  padding: 0 20rpx 20rpx;
  border-radius: 6rpx;
  width: calc(100% - 30rpx);
  box-sizing: border-box;
}

.charts-wrapper {
  width: 100%;
  overflow: hidden;
  border-radius: 6rpx;
}

/* 数据更新时间 */
.update-time {
  color: #86909c;
  font-size: 24rpx;
  text-align: center;
  padding: 20rpx 15rpx;
  margin-top: 10rpx;
}

/* 底部留白 */
.bottom-space {
  height: 30rpx;
}

/* 滚动条样式（仅移动模式） */
.table-scroll-container::-webkit-scrollbar {
  height: 8rpx;
}

.table-scroll-container::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4rpx;
}

.table-scroll-container::-webkit-scrollbar-thumb {
  background: #e53e3e;
  border-radius: 4rpx;
}

/* 可视化切换样式 */
.visualization-toggle {
  margin: 10rpx 15rpx; 
  width: calc(100% - 30rpx); 
  display: flex; 
  justify-content: flex-end; 
  align-items: center; 
  padding: 10rpx 0;
}

.visualization-icon {
  display: inline-block; 
  transition: transform 0.3s ease; 
  font-size: 28rpx; 
  margin-left: 8rpx; 
}
</style>
